import { DataTypes, Model, type Optional } from 'sequelize'
import sequelize from '../config'

// 评论属性接口
export interface CommentAttributes {
  id: number
  content: string
  postId: number
  authorId: number
  parentId?: number // 父评论ID，用于回复功能
  likeCount: number
  createdAt?: Date
  updatedAt?: Date
}

// 创建评论时的可选属性
export type CommentCreationAttributes = Optional<CommentAttributes, 'id' | 'parentId' | 'likeCount' | 'createdAt' | 'updatedAt'>

// 评论模型类
export class Comment extends Model<CommentAttributes, CommentCreationAttributes> implements CommentAttributes {
  declare id: number
  declare content: string
  declare postId: number
  declare authorId: number
  declare parentId?: number
  declare likeCount: number
  declare readonly createdAt: Date
  declare readonly updatedAt: Date
}

// 定义评论模型
Comment.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: false,
      comment: '评论内容'
    },
    postId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '所属帖子ID'
    },
    authorId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '评论作者ID'
    },
    parentId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '父评论ID，用于回复功能'
    },
    likeCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '点赞数量'
    }
  },
  {
    sequelize,
    tableName: 'comments',
    timestamps: true,
    indexes: [
      {
        fields: ['postId']
      },
      {
        fields: ['authorId']
      },
      {
        fields: ['parentId']
      },
      {
        fields: ['createdAt']
      }
    ]
  }
)

export default Comment
